package net.stogi.unicore.beyond.ui.client.taskeditor.taskoutline;

import net.stogi.common.mvp.core.behavior.Behavior;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;

class PropertyEditorWidget extends Window implements PropertyEditorView {

	private final Button cancelButton = new Button();

	private final FormPanel mainPanel = new FormPanel();

	private final TextField<String> nameTextField = new TextField<String>();

	private final Button okButton = new Button();

	public PropertyEditorWidget() {
		initComposite();
		initI18n();
		initLayout();
	}

	@Override
	public void appear() {
		show();
	}

	@Override
	public void clear() {
		nameTextField.setValue(null);
		nameTextField.clearInvalid();
	}

	@Override
	public String collectName() {
		return nameTextField.getValue();
	}

	@Override
	public void disappear() {
		hide();
	}

	@Override
	public void displayName(String name) {
		nameTextField.setValue(name);
	}

	@Override
	public void invalidName(String message) {
		nameTextField.forceInvalid(message);
	}

	@Override
	public void setCancelBehavior(final Behavior behavior) {
		cancelButton.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				behavior.behave();
			}
		});
	}

	@Override
	public void setOkBehavior(final Behavior behavior) {
		okButton.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				behavior.behave();
			}
		});
	}

	private void initComposite() {
		nameTextField.setAllowBlank(false);
		
		mainPanel.setAutoHeight(true);
		mainPanel.setBodyBorder(false);
		mainPanel.setHeaderVisible(false);
		mainPanel.setLabelSeparator("");

		setClosable(false);
		setFrame(true);
		setLayout(new FitLayout());
		setModal(true);
		setResizable(false);
		setWidth("30%");
	}

	private void initI18n() {
		nameTextField.setFieldLabel("Name");
		cancelButton.setText("Cancel");
		okButton.setText("Ok");
		setHeading("PropertyEditor");
	}

	private void initLayout() {
		mainPanel.add(nameTextField, new FormData("-22"));
		add(mainPanel);
		addButton(okButton);
		addButton(cancelButton);
	}
}
